<!--
 * @Author: xuzehan h935351619@163.com
 * @Date: 2024-11-28 14:14:41
 * @LastEditors: xuzehan h935351619@163.com
 * @LastEditTime: 2024-12-04 16:50:06
 * @FilePath: \qlck-vue\src\views\ErrorRate\ErrorRateTest.vue
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
-->
<template>
  <a-card :bordered="false">
    <!-- 查询区域 -->
    <div class="table-page-search-wrapper">
      <a-form-model layout="inline" ref="ruleForm" :model="ruleForm" :rules="rules111">
        <a-row :gutter="24">
          <!-- <a-col :md="4" :sm="12">
            <a-form-model-item label="测试模式" prop='testMode'>
              <j-dict-select-tag v-model="ruleForm.testMode" placeholder="请选择测试模式" dictCode="test_mode_db" />
            </a-form-model-item>
          </a-col> -->
          <!-- <a-col :md="4" :sm="12" v-if='ruleForm.testMode == "导频模式"'> -->
          <a-col :md="4" :sm="12">
            <a-form-model-item label="通道号" prop="startTdh">
              <a-input-number v-model="ruleForm.startTdh" style="width:100%" placeholder="请输入1-380"></a-input-number>
            </a-form-model-item>
          </a-col>
          <a-col :md="4" :sm="12">
            <a-form-model-item label="符号速率" prop="symbolRate">
              <j-dict-select-tag v-model="ruleForm.symbolRate" placeholder="请选择符号速率" dictCode="symbol_rate_db" />
            </a-form-model-item>
          </a-col>
          <!-- <a-col :md="6" :sm="12" v-if='ruleForm.testMode == "轮询模式"'>
            <a-form-model-item label="特征码" prop='errorSourceData'>
              <a-input placeholder="请输入特征码(0~F的16进制数)" :maxLength="444" v-model="ruleForm.errorSourceData"></a-input>
            </a-form-model-item>
          </a-col> -->
          <a-col :md="4" :sm="8">
            <span style="float: left;overflow: hidden;" class="table-page-search-submitButtons">
              <a-button type="primary" @click="handleStart()">开始</a-button>
              <!-- <a-button type="primary"  style="margin-left: 8px" @click="onClick" :disabled="disabled">开始</a-button> -->
              <a-button type="primary" style="margin-left: 8px" @click="handleStop" :disabled="!disabled"
                >停止</a-button
              >
              <!-- <a-button type="primary"
                style="margin-left: 8px" @click="handleReset">复位</a-button> -->
            </span>
          </a-col>
          <span v-if="time < 60" style="color: red; font-size: 25px;">{{ time }}</span>
        </a-row>
      </a-form-model>
    </div>
    <!-- 查询区域-END -->

    <!-- 操作按钮区域 -->
    <div class="table-operator">
      <!-- <a-button type="primary" icon="download" @click="handleExportXls('帧信息')">导出</a-button>
      <a-dropdown v-if="selectedRowKeys.length > 0">
        <a-menu slot="overlay">
          <a-menu-item key="1" @click="batchDel">
            <a-icon type="delete" />删除
          </a-menu-item>
        </a-menu>
        <a-button style="margin-left: 8px">
          批量操作
          <a-icon type="down" />
        </a-button>
      </a-dropdown> -->
    </div>

    <!-- table区域-begin -->
    <div>
      <a-divider orientation="left" style="color:#fff">测试结果</a-divider>
      <a-descriptions :column="4">
        <a-descriptions-item label="总帧数">
          {{ desData.frameTotal }}
        </a-descriptions-item>
        <a-descriptions-item label="总误码率">
          {{ Number(desData.errorFramePercentage * 100).toFixed(2) }}%
        </a-descriptions-item>
        <a-descriptions-item label="总误码数">
          {{ desData.errorFrameTotal }}
        </a-descriptions-item>
      </a-descriptions>
      <div class="tdsjxs">
        <div v-for="i in listData" :key="i.tdh" style="width:20%;border:1px solid;padding:10px;height:70px">
          <div>{{ i.tdh }}</div>
          <div>({{ i.frameTotal }}/{{ i.errorFrameTotal }}/{{ Number(i.errorFramePercentage * 100).toFixed(2) }}%)</div>
        </div>
      </div>
    </div>
  </a-card>
</template>

<script>
import { getAction, httpAction } from '@/api/manage'

export default {
  name: 'NmcFrameInfoList',
  components: {},
  data() {
    let validateErrorSourceData = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入误码源数据'))
        return
      }

      if (value.length % 2 != 0) {
        callback(new Error('请确保输入长度为偶数'))
        return
      }

      if (!/^[0-9A-F]+$/.test(value)) {
        callback(new Error('请确保输入数据时16进制字符串(全大写)'))
        return
      }

      callback()
    }
    return {
      rules111: {
        // testMode: [
        //   { required: true, message: '请选择测试模式', trigger: 'blur' },
        // ],
        startTdh: [{ required: true, message: '请输入通道号', trigger: 'blur' }],
        symbolRate: [{ required: true, message: '请选择符号速率', trigger: 'change' }],
        errorSourceData: [
          { validator: validateErrorSourceData },
          { required: true, message: '请输入误码源数据', trigger: 'blur' }
        ]
      },
      url: {
        list: '/frameInfo/nmcFrameInfo/list',
        add: '/plan/qlTestPlan/add',
        stop: '/plan/qlTestPlan/stopTestPlan',
        reset: '/Reset',
        getRunningTestPlan: '/plan/qlTestPlan/getRunningTestPlan',
        getPassagewayTestPlanStatistics: '/dcpr/dcprPassagewayHistoryInfo/getPassagewayTestPlanStatistics'
      },
      desData: {
        frameTotal: 0,
        errorFramePercentage: 0,
        errorFrameTotal: 0
      },
      disabled: false,
      ruleForm: {
        testMode: '导频模式',
        startTdh: '',
        symbolRate: '900',
        // symbolRate: '',
        errorSourceData: '',
        tdhType: ''
      },
      testId: '',
      timer: null,
      timer1: null,
      listData: [
        // {tdh:1,frameTotal:20,errorFrameTotal:2,errorFramePercentage:10},
      ],
      time: 60
    }
  },
  created() {
    // this.getListData();
    this.loadData()
  },
  mounted() {
    document.addEventListener('visibilitychange', this.handleVisibilityChange)
    // window.onfocus = this.startTimer(); // 页面聚焦时开始定时任务
    // window.onblur = this.stopTimerFun(); // 页面失去焦点时停止定时任务
  },
  computed: {
    importExcelUrl: function() {
      return `${window._CONFIG['domianURL']}/${this.url.importExcelUrl}`
    }
  },
  destroyed() {
    this.stopTimerFun()
  },
  methods: {
    handleVisibilityChange() {
      if (document.visibilityState === 'visible') {
        // 页面变为可见，重新开始定时器
        this.startTimer()
      } else if (document.visibilityState === 'hidden') {
        // 页面变为不可见，清除定时器
        this.stopTimerFun()
      }
    },
    getRunningTestPlan() {
      getAction(this.url.getRunningTestPlan)
        .then(res => {
          if (res.success) {
            if (res.result) {
              this.disabled = true
              this.testId = res.result.id
              this.ruleForm = Object.assign({}, res.result)
              this.ruleForm.symbolRate = '900'
              this.ruleForm.testMode = '导频模式'
            } else {
              this.disabled = false
              this.testId = ''
              this.stopTimerFun()
            }
          } else {
            this.$message.error(res.message)
          }
        })
        .catch(error => {
          console.error('Promise rejected:', error)
          // 这里可以处理错误，或者再次抛出错误
        })
    },
    loadData() {
      getAction(this.url.getRunningTestPlan)
        .then(res => {
          if (res.success) {
            if (res.result) {
              this.disabled = true
              this.testId = res.result.id
              this.ruleForm = Object.assign({}, res.result)
              this.ruleForm.testMode = '导频模式'
              this.ruleForm.symbolRate = '900'
              this.ruleForm.errorSourceData = ''
              this.getPassagewayInfo()
              this.startTimer()
            } else {
              this.disabled = false
            }
          } else {
            this.$message.error(res.message)
          }
        })
        .catch(error => {
          console.error('Promise rejected:', error)
          // 这里可以处理错误，或者再次抛出错误
        })
    },
    startTimer() {
      //每5秒刷新一次通道测试信息
      if (!this.testId) return
      if (this.timer) clearInterval(this.timer)

      this.timer = setInterval(() => {
        this.getPassagewayInfo()
        this.getRunningTestPlan()
      }, 9000)
    },
    stopTimerFun() {
      clearInterval(this.timer)
    },
    getPassagewayInfo() {
      //获取通道信息
      getAction(this.url.getPassagewayTestPlanStatistics, { planId: this.testId })
        .then(res => {
          if (res.success) {
            if (res.result) {
              //每5秒刷新一次通道测试信息
              this.listData = [...res.result.passagewayItemVoList]
              this.desData = Object.assign({}, res.result)
            } else {
            }
          } else {
            this.$message.error(res.message)
          }
        })
        .catch(error => {
          console.error('Promise rejected:', error)
          // 这里可以处理错误，或者再次抛出错误
        })
    },
    handleStart() {
      this.$refs.ruleForm.validate(valid => {
        if (valid) {
          let data = {
            endTdh: this.ruleForm.startTdh,
            startTdh: this.ruleForm.startTdh,
            symbolRate: this.ruleForm.symbolRate,
            testMode: this.ruleForm.testMode,
            errorSourceData: this.ruleForm.errorSourceData
          }
          // console.log('this.ruleForm.testMode', this.ruleForm);
          // console.log('data',data);
          // return
          // if (data == '导频模式') {
          //   data.endTdh = this.ruleForm.startTdh
          // } else if (this.ruleForm.testMode == '轮询模式') {
          //   data.startTdh = 1
          //   data.endTdh = 380
          // }
          httpAction(this.url.add, data, 'post').then(res => {
            if (res.success) {
              this.$message.success(res.message)
              this.loadData()
            } else {
              this.$message.error(res.message)
            }
          })
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    handleStop() {
      getAction(this.url.stop, { id: this.testId }).then(res => {
        this.stopTimerFun()
        if (res.success) {
          this.$message.success(res.message)
          this.testId = ''
          this.stopTimerFun()
          this.disabled = false
        } else {
          this.$message.error(res.message)
        }
      })
    },
    handleReset() {
      getAction(this.url.reset).then(res => {
        if (res.success) {
          this.$message.success(res.message)
        } else {
          this.$message.error(res.message)
        }
      })
    },
    getListData() {
      getAction(this.url.list).then(res => {
        this.listData = res.result.records
      })
    },
    onClick() {
      // 这里是“测试时长60s，自动结束”的逻辑
      let timerId = setInterval(() => {
        if (this.time > 0) {
          this.time--
        } else {
          clearInterval(timerId)
        }
      }, 1000)
    }
  }
}
</script>
<style scoped lang="less">
@import '~@assets/less/common.less';

.tdsjxs {
  display: flex;
  flex-wrap: wrap;
  // padding:20px;
  height: calc(100vh - 300px);
  overflow-y: scroll;
  // border: 1px solid;
}
</style>
